/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* sum = nullptr;
        auto i = l1;
        auto j = l2;
        auto k = &sum;
        while (i || j) {
            if (i && j) {
                *k = new ListNode(i->val + j->val);
                i = i->next;
                j = j->next;
                k = &(*k)->next;
            } else if (i) {
                *k = new ListNode(i->val);
                i = i->next;
                k = &(*k)->next;
            } else if (j) {
                *k = new ListNode(j->val);
                j = j->next;
                k = &(*k)->next;
            }
        }

        for (auto l = sum; l != nullptr; l = l->next) {
            if (l->val >= 10) {
                if (l->next == nullptr) {
                    l->next = new ListNode(l->val / 10);
                } else {
                    l->next->val += l->val / 10;
                }
                l->val %= 10;
            }
        }
        return sum;
    }
};
